package servlet.song;

import pojo.Songs;
import service.SongsService;
import service.impl.SongsServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;

@WebServlet("/song/add")
@MultipartConfig(fileSizeThreshold = 4 * 1024, maxFileSize = 100000 * 1024)
public class Insert extends HttpServlet {

    SongsService songsService = new SongsServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 获取上传的歌曲文件部分
        Part songFile = req.getPart("song_file");
        String songFileName = songFile.getSubmittedFileName();

        // 获取文件存储路径（这里使用相对路径）

        String songFilePath = req.getServletContext().getRealPath("/") + "/static/songs/" + songFileName;

        // 将文件保存到指定目录

        songFile.write(songFilePath);

        // 获取其他表单数据
        int  songId = Integer.parseInt(req.getParameter("songId"));
        String title = req.getParameter("title");
        String description = req.getParameter("description");
        int uploaderId = Integer.parseInt(req.getParameter("uploaderId"));
       int  categoryId = Integer.parseInt(req.getParameter("categoryId"));

        // 创建 Song 对象并填充数据
        Songs song = new Songs(songId, title, "/static/songs/" + songFileName, description, uploaderId, categoryId);

        // 调用服务层插入数据库
        boolean isAdded = songsService.insert(song);

        // 响应处理
        resp.setContentType("text/html;charset=UTF-8");
        if (isAdded) {
            // 插入成功，重定向到歌曲列表页面（或其他页面）
            resp.sendRedirect("/song/list.jsp");
        } else {
            // 插入失败，返回错误提示
            resp.getWriter().write("<script>alert('歌曲添加失败');</script>");
        }
    }
}
